package com.qidian.buy.controller;

import com.qidian.buy.util.pojo.QDResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @Author 郭浩
 */
@RestController
@RequestMapping("/image")
@CrossOrigin
public class ImageUploadController {
    @Value("${image-local-path}")
    private String imageLocalPath;
    @Value("${image-server-path}")
    private String imageServerPath;
    @RequestMapping("/upload")
    public QDResult upload(@RequestParam(name = "file") MultipartFile[] files){
        List<String> imageUrls = new ArrayList<>();
        StringBuilder sb = new StringBuilder("上传失败的图片：");
        for (MultipartFile file : files){
            // 取出名字
            String originalFilename = file.getOriginalFilename();
            // 后缀
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            //  生成文件名
            String fname = UUID.randomUUID().toString().replace("-","_")+(new Random().nextInt(90)+10)+ext;
            //  磁盘上的目标文件
            File f = new File(imageLocalPath+fname);
            // 拷贝文件
            try {
                file.transferTo(f);
                imageUrls.add(imageServerPath+fname);
            } catch (IOException e) {
                e.printStackTrace();
                sb.append(originalFilename+",");
            }
        }
        return QDResult.ok(sb.toString(),imageUrls);
    };
}
